import { useEffect, useState } from 'react'
import Taro, { FC, useRouter } from '@tarojs/taro'
import { Subject, Subscription } from 'rxjs';
import { debounceTime, map, switchMap, tap } from 'rxjs/operators';
import { AtForm, AtSwitch, AtInput, AtIcon } from 'taro-ui'
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/switch.scss";
import { View, Text, Button } from '@tarojs/components'

import { EditRoomParams } from '@/models/request/roomReq';
import { onEmit } from '@/utils/rxHelpers';
import { getLogger } from '@/utils/log';
import { useRoomUiFacade } from '@/hooks/useRoomUiFacade';
import { rsgPwdNum } from '@/utils/regexRule';

import "taro-ui/dist/style/components/button.scss" // 按需引入 
import './index.scss'

//密码设置
export const PwdSetting: FC = () => {
  const logger = getLogger("/pages/liveRoom/pwdSetting");
  const [
    roomFacade, , , , , , , , , , , , , , , , , , , , , , passwd,] = useRoomUiFacade();

  const router = useRouter();
  const roomId = router.params.roomId || "";
  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState(initSubject);
  const [content, setContent] = useState(passwd)
  const [open, setOpen] = useState(false)

  const handleChange = (value) => {
    setOpen(value)
    if (open === true) {
      setContent('');
      roomFacade.editRoomPwd({
        roomId: roomId,
        passwd: '',
      })

    }
  }
  const handleBlur1 = (value) => {
    rsgPwdNum(value)
  }


  const handleChange1 = (value) => {
    setContent(value)
  }

  const checkNum = (num) => {
    //验证必须是数字
    if (isNaN(num)) {
      alert("请输入数字！");
      return false;
    }
    //验证必须是4位
    if (num.match(/\d/g).length != 4) {
      alert("您的输入必须为4位数字!");
      return false;
    }
    if (num.match(/\d/g).length > 4) {
      alert("您的输入超过了4位数字!");
      return false;
    }
    if (num.match(/\d/g).length < 4) {
      alert("您的输入不足了4位数字!");
      return false;
    }
  }


  //把按钮点击事件转化为observable
  const editLive$ = emitter.asObservable()
    .pipe(
      //防抖动(防重复)
      debounceTime(500),
      map(obj => obj as EditRoomParams),
      //接收按钮点击的参数
      tap(editLiveObj => {
        console.log("editLiveObj:", editLiveObj)
        //验证必须是4位
        if (!editLiveObj.passwd || editLiveObj.passwd.length != 4) {
          throw Taro.showToast({
            title: '您的输入必须为4位数字!',
            icon: 'none',
            duration: 2000
          })
        }
        rsgPwdNum(editLiveObj.passwd as string)
      }),
      switchMap(roomFacade.editRoomPwd)
    )

  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<string>(
        editLive$,
        () => {
          Taro.showToast({
            title: '保存成功',
            icon: 'none',
            duration: 2000
          });
          setTimeout(() => {
            Taro.navigateBack({
              delta: 1
            })
          }, 1000)
        },
        err => {
          logger.ERROR("保存信息失败！", err)
          setEmitter(initSubject);
        }
      ),

    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])

  useEffect(() => {
    if (passwd) {
      setContent(passwd)
      setOpen(true)
    }
  }, [passwd])

  return (
    <View className='index'>
      <View className='main'>
        <AtForm>
          <AtSwitch title='密码启用' checked={open} onChange={handleChange} color={MAIN_COLOR} />
        </AtForm>
        {
          open && (
            <View>
              <AtForm>
                <AtInput
                  className='input'
                  name='value1'
                  title='观看密码'
                  type='number'
                  placeholder='设置4位密码'
                  value={content}
                  onChange={handleChange1.bind(this)}
                  onBlur={handleBlur1.bind(this)}
                >
                  <AtIcon value='chevron-right' size='20' color='#666666'></AtIcon>
                </AtInput>
              </AtForm>
              <Button className='bt' onClick={() => emitter.next({
                roomId: roomId,
                passwd: content,
              } as EditRoomParams)}
              >
                <Text className='check'>确认</Text>
              </Button>

            </View>
          )
        }

      </View>
    </View>
  )
}
export default PwdSetting